package com.hopedove.yieldmanage.adapter;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;

import com.hopedove.yieldmanage.R;
import com.hopedove.yieldmanage.entity.ProductQueryEntity;
import com.hopedove.yieldmanage.utils.SharedPreUtil;

import java.util.List;


public class QueryListAdapter extends BaseAdapter {
    private Context mContext;

    private List<ProductQueryEntity> mProductList;

    /**
     * 记录点击的下标
     **/
    private int mIndex = -1;
    /**
     * 记录点击的edittext
     **/
    private EditText mEditText;
    // 编辑权限
    private String mEditPermission = "";

    public QueryListAdapter(Context context, List<ProductQueryEntity> objects) {
        super();
        mContext = context;

        // 这里集合用=号赋值，改变内部productlist 外部list一样会变
        mProductList = objects;

        mEditPermission = (String) SharedPreUtil.getValue(mContext, SharedPreUtil.CM0140202, "");
    }

    @Override
    public int getCount() {

        return mProductList.size();
    }

    @Override
    public Object getItem(int position) {
        return mProductList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) { // 获得当前项的示例
        final ProductQueryEntity product;
        product = (ProductQueryEntity) getItem(position);
        View view;
        final ViewHolder viewholder;
        if (convertView == null) {
            view = LayoutInflater.from(mContext).inflate(R.layout.query_list_item, parent, false);

            viewholder = new ViewHolder(view);

            view.setTag(viewholder);
        } else {
            view = convertView;
            viewholder = (ViewHolder) view.getTag();
        }

        // 根据权限设置 edittext的编辑状态
        if ("1".equals(mEditPermission)) {
            viewholder.standardSpeedEt.setEnabled(true);
            viewholder.standardRateEt.setEnabled(true);
            viewholder.standardOnjobEt.setEnabled(true);
            viewholder.standardQuotaEt.setEnabled(true);
            viewholder.checkBox.setEnabled(true);
        } else {
            viewholder.standardSpeedEt.setEnabled(false);
            viewholder.standardRateEt.setEnabled(false);
            viewholder.standardOnjobEt.setEnabled(false);
            viewholder.standardQuotaEt.setEnabled(false);
            viewholder.checkBox.setEnabled(false);
        }

        viewholder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (mOnCheckClickListener != null) {
                    mOnCheckClickListener.onClick(position, isChecked);
                }
            }
        });

        /******************************************************** 分割线 *******************************************************/
        /******************************************** 解决edittext中数据丢失、错乱问题，共5个步骤 ****************************************/

        /** 1、为了避免TextWatcher在第2步被调用，提前将他移除。 **/
        if (viewholder.standardSpeedEt.getTag() instanceof TextWatcher) {
            viewholder.standardSpeedEt.removeTextChangedListener((TextWatcher) (viewholder.standardSpeedEt.getTag()));
        }
        if (viewholder.standardRateEt.getTag() instanceof TextWatcher) {
            viewholder.standardRateEt.removeTextChangedListener((TextWatcher) (viewholder.standardRateEt.getTag()));
        }
        if (viewholder.standardOnjobEt.getTag() instanceof TextWatcher) {
            viewholder.standardOnjobEt.removeTextChangedListener((TextWatcher) (viewholder.standardOnjobEt.getTag()));
        }
        if (viewholder.standardQuotaEt.getTag() instanceof TextWatcher) {
            viewholder.standardQuotaEt.removeTextChangedListener((TextWatcher) (viewholder.standardQuotaEt.getTag()));
        }

        /** 第2步：移除TextWatcher之后，设置EditText的Text。当然其他组件也在这赋值 **/
        viewholder.jobDateTv.setText(product.JOBDATE);
        viewholder.jobNumTv.setText(product.JOB_NUM);
        viewholder.classesTv.setText(product.CLASSES);
        viewholder.machineNoTv.setText(product.MACHINENO);
        viewholder.productTypeTv.setText(product.PRODUCTTYPE);
        viewholder.clothNoTv.setText(product.CLOTHNO);
        viewholder.standardSpeedEt.setText(product.STANDARD_SPEED);
        viewholder.standardRateEt.setText(product.STANDARD_RATE);
        viewholder.standardOnjobEt.setText(product.STANDARD_ONJOB);
        viewholder.standardQuotaEt.setText(product.STANDARD_QUOTA);
        viewholder.machineSpeedTv.setText(product.MACHINE_SPEED);
        viewholder.rotationRateTv.setText(product.ROTATION_RATE);
        viewholder.zpsTv.setText(product.ZPS);
        viewholder.reasonsTv.setText(product.REASONS);
        viewholder.stopHoursTv.setText(product.STOPHOURS);

        // 设置checkbox状态
        if (product.isChecked == true) {
            viewholder.checkBox.setChecked(true);
        } else {
            viewholder.checkBox.setChecked(false);
        }

        /** 3、实例化Textwatcher监听器 **/
        MyTextWatcher standardSpeedWatcher = new MyTextWatcher(viewholder.standardSpeedEt, position);
        MyTextWatcher standardRateWatcher = new MyTextWatcher(viewholder.standardRateEt, position);
        MyTextWatcher standardOnjobWatcher = new MyTextWatcher(viewholder.standardOnjobEt, position);
        MyTextWatcher standardQuotaWatcher = new MyTextWatcher(viewholder.standardQuotaEt, position);

        /** 4、设置edittext的监听器 **/
        viewholder.standardSpeedEt.addTextChangedListener(standardSpeedWatcher);
        viewholder.standardRateEt.addTextChangedListener(standardRateWatcher);
        viewholder.standardOnjobEt.addTextChangedListener(standardOnjobWatcher);
        viewholder.standardQuotaEt.addTextChangedListener(standardQuotaWatcher);

        /** 5、设置edittext的tag 传入textwatcher **/
        viewholder.standardSpeedEt.setTag(standardSpeedWatcher);
        viewholder.standardRateEt.setTag(standardRateWatcher);
        viewholder.standardOnjobEt.setTag(standardOnjobWatcher);
        viewholder.standardQuotaEt.setTag(standardQuotaWatcher);

        /****************************************************** 分割线 ***********************************************************/
        /******************************************* 解决edittext焦点丢失问题 *******************************************************/

        /** 1、设置touch监听器，在点击的时候记录当前点击的位置 **/
        viewholder.standardSpeedEt.setOnTouchListener(new MyTouchListener(viewholder.standardSpeedEt, position));
        viewholder.standardRateEt.setOnTouchListener(new MyTouchListener(viewholder.standardRateEt, position));
        viewholder.standardOnjobEt.setOnTouchListener(new MyTouchListener(viewholder.standardOnjobEt, position));
        viewholder.standardQuotaEt.setOnTouchListener(new MyTouchListener(viewholder.standardQuotaEt, position));

        /** 2、恢复焦点 **/
        if (mIndex != -1) {
            // 在点击了数据的情况下，执行下面逻辑
            if (mIndex == position) {
                // 如果当前的行下标和点击事件中保存的index一致，手动为EditText设置焦点。
                // 获取了焦点，但是光标不闪，重新调用setText方法即可
                final int id = mEditText.getId();
                if (id == R.id.query_item_standardSpeedEt) {
                    viewholder.standardSpeedEt.requestFocus();
                    viewholder.standardSpeedEt.setText(viewholder.standardSpeedEt.getText().toString());
                    viewholder.standardSpeedEt.setSelection(viewholder.standardSpeedEt.getText().length());
                } else if (id == R.id.query_item_standardRateEt) {
                    viewholder.standardRateEt.requestFocus();
                    viewholder.standardRateEt.setText(viewholder.standardRateEt.getText().toString());
                    viewholder.standardRateEt.setSelection(viewholder.standardRateEt.getText().length());
                } else if (id == R.id.query_item_standardOnjobEt) {
                    viewholder.standardOnjobEt.requestFocus();
                    viewholder.standardOnjobEt.setText(viewholder.standardOnjobEt.getText().toString());
                    viewholder.standardOnjobEt.setSelection(viewholder.standardOnjobEt.getText().length());
                } else if (id == R.id.query_item_standardQuotaEt) {
                    viewholder.standardQuotaEt.requestFocus();
                    viewholder.standardQuotaEt.setText(viewholder.standardQuotaEt.getText().toString());
                    viewholder.standardQuotaEt.setSelection(viewholder.standardQuotaEt.getText().length());
                }
            } else {
                viewholder.standardSpeedEt.clearFocus();
                viewholder.standardRateEt.clearFocus();
                viewholder.standardOnjobEt.clearFocus();
                viewholder.standardQuotaEt.clearFocus();

            }

        }

        /****************************************************** 分割线 ***********************************************************/

        return view;

    }

    /**
     * 设置光标位置
     *
     * @param index
     */
    public void setFocusIndex(int index) {
        mIndex = index;
    }

    private onCheckClickListener mOnCheckClickListener;

    /**
     * 设置选择框接口
     */
    public void setOnCheckClickListener(onCheckClickListener onCheckClickListener) {
        mOnCheckClickListener = onCheckClickListener;
    }

    /**
     * 选择框接口
     *
     * @author zhu_yu
     */
    public interface onCheckClickListener {
        public void onClick(int position, boolean isChecked);
    }

    private class MyTouchListener implements OnTouchListener {
        private int position;
        private EditText editText;

        public MyTouchListener(EditText editText, int position) {
            this.editText = editText;
            this.position = position;
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                mIndex = position;
                mEditText = editText;
                editText.requestFocus();
                editText.setText(editText.getText().toString());
                // editText.setSelection(editText.getText().length());
                Log.d("mIndex", mIndex + "");
                // String str=editText.getText().toString();
                // Log.d("editText:text",str );
            }
            return false;
        }

    }

    /**
     * 文本变化监听器.随时保存用户输入的值到list中
     *
     * @author zhu_yu
     * @Description<功能详细描述>
     * @Version [版本号, 2017-6-6]
     */
    private class MyTextWatcher implements TextWatcher {

        private EditText editText;
        private int position;

        public MyTextWatcher(EditText editText, int position) {
            this.editText = editText;
            this.position = position;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            final int id = editText.getId();
            if (id == R.id.query_item_standardSpeedEt) {
                mProductList.get(position).STANDARD_SPEED = s.toString();
            } else if (id == R.id.query_item_standardRateEt) {
                mProductList.get(position).STANDARD_RATE = s.toString();
            } else if (id == R.id.query_item_standardOnjobEt) {
                mProductList.get(position).STANDARD_ONJOB = s.toString();
            } else if (id == R.id.query_item_standardQuotaEt) {
                mProductList.get(position).STANDARD_QUOTA = s.toString();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    /**
     * 对控件实例进行缓存
     */
    class ViewHolder {
        int position;

        /**
         * 日期
         **/
        TextView jobDateTv;
        /**
         * 工号
         **/
        TextView jobNumTv;
        /**
         * 班次
         **/
        TextView classesTv;
        /**
         * 车号
         **/
        TextView machineNoTv;
        /**
         * 胚布类型
         **/
        TextView productTypeTv;
        /**
         * 布号
         **/
        TextView clothNoTv;
        /**
         * 标准车速
         **/
        EditText standardSpeedEt;
        /**
         * 标准转数
         **/
        EditText standardRateEt;
        /**
         * 标准开台
         **/
        EditText standardOnjobEt;
        /**
         * 标准定额
         **/
        EditText standardQuotaEt;
        /**
         * 车速
         **/
        TextView machineSpeedTv;
        /**
         * 转数
         **/
        TextView rotationRateTv;
        /**
         * 总匹数
         **/
        TextView zpsTv;
        /**
         * 其他原因
         **/
        TextView reasonsTv;
        /**
         * 停台小时
         **/
        TextView stopHoursTv;
        /**
         * 记录是否被选择
         **/
        CheckBox checkBox;

        public ViewHolder(View view) {

            jobDateTv = view.findViewById(R.id.query_item_jobDateTv);
            jobNumTv = view.findViewById(R.id.query_item_jobNumTv);
            classesTv = view.findViewById(R.id.query_item_classesTv);
            machineNoTv = view.findViewById(R.id.query_item_machineNoTv);
            productTypeTv = view.findViewById(R.id.query_item_productTypeTv);
            clothNoTv = view.findViewById(R.id.query_item_clothNoTv);
            standardSpeedEt = view.findViewById(R.id.query_item_standardSpeedEt);
            standardRateEt = view.findViewById(R.id.query_item_standardRateEt);
            standardOnjobEt = view.findViewById(R.id.query_item_standardOnjobEt);
            standardQuotaEt = view.findViewById(R.id.query_item_standardQuotaEt);
            machineSpeedTv = view.findViewById(R.id.query_item_machineSpeedTv);
            rotationRateTv = view.findViewById(R.id.query_item_rotationRateTv);
            zpsTv = view.findViewById(R.id.query_item_zpsTv);
            reasonsTv = view.findViewById(R.id.query_item_reasonsTv);
            stopHoursTv = view.findViewById(R.id.query_item_stopHoursTv);
            checkBox = view.findViewById(R.id.query_item_checkBox);

        }

    }

}
